package controllers

import models._
import play.api._
import play.api.Play.current
import play.api.cache.Cache
import play.api.mvc._
import util._
import play.api.data.Form
import play.api.data.Forms._

object Blogs extends Controller {

  def list(page: Int) = ActionWithTags {
    implicit request =>
      val articleList = Article.queryByPages(page).map(article => (article.id, article.title, article.time, article.shortcontent, article.userid)) collect {
        case (id, title, otime, ocontent, userId) =>
          (id, title, timeFormatter(otime.get.getTime()), ocontent.getOrElse(""), Tag.findTags(id), User.findUser(userId).username)
      }
      val pages = Article.getTotalPage
      Ok(views.html.blog.list(articleList, pages, page))
  }

  def tag(tag: String, page: Int) = ActionWithTags {
    implicit request =>
      val (pages, articles) = Article.queryByTagAndPages(tag, page)
      val articleList = articles.map(article => (article.id, article.title, article.time, article.shortcontent, article.userid)) collect {
        case (id, title, otime, ocontent, userId) =>
          (id, title, timeFormatter(otime.get.getTime()), ocontent.getOrElse(""), Tag.findTags(id), User.findUser(userId).username)
      }
      Ok(views.html.blog.tag(articleList, pages, page, tag))
  }

  /**
   * 根据id来查找文章
   */
  def blog(id: Int) = ActionWithTags {
    implicit request =>
      val list = Article.queryById(id)
      if (list.size == 0) {
        Redirect(routes.Blogs.list(1))
      } else {
        val articleRow: Tables.ArticleRow = list(0)
        val article: (String, String, String, List[String], Int) = (articleRow.title,
          timeFormatter(articleRow.time.get.getTime()),
          articleRow.content, Tag.findTags(id), articleRow.id)
        Ok(views.html.blog.article(article))
      }
  }

  //修改文章
  def update(id: Int) = ActionWithUser {
    implicit request =>
      val articles = Article.queryById(id)
      if (articles.size != 1) {
        BadRequest
      } else {
        val article = articles(0)
        val form = articleForm.bind(Map[String, String]("id" -> (article.id + ""), "title" -> article.title, "tags" -> Tag.findTags(id).mkString(","), "content" -> article.content))
        Ok(views.html.blog.create(form))
      }
  }
  //删除文章
  def delete(id: Int) = ActionWithUser {
    implicit request =>
      Article.delete(id)
      Redirect(routes.Blogs.list(1))
  }
  //新建文章
  def create = ActionWithUser {
    implicit request =>
      Ok(views.html.blog.create(articleForm))
  }

  //保存文章
  def save = ActionWithUser {
    implicit request =>
      val form = articleForm.bindFromRequest
      form.fold(hasErrors = {
        form => Ok(views.html.blog.create(articleForm))
      }, success = {
        tuple =>
          val userid = request.session.get(Constants.UserId)
          //如果无法得到userId那说明系统出现了问题
          if (!userid.isDefined) {
            InternalServerError.withNewSession
          } else {
            val shortContent = Some(if (tuple._4.length() < 50) tuple._4 else tuple._4.substring(0, 50))
            //得到标签列表
            val pretags = tuple._3.split(",").toList
            val tags = pretags.filter(tag => tag != null && tag.trim() != "")
            val uid = request.session.get(Constants.UserId).get.toInt
            //如果ID小于等于0 说明是创建的 反之是修改的
            if (tuple._1 <= 0) {
              val time = Some(new java.sql.Timestamp(new java.util.Date().getTime()))
              val row = Tables.ArticleRow(tuple._1, tuple._2, tuple._4, shortContent, time, uid)
              models.Article.save(row, tags)
            } else {
              val row = Tables.ArticleRow(tuple._1, tuple._2, tuple._4, shortContent, None, uid)
              models.Article.update(row, tags)
            }
            refreshTags
            Redirect(routes.Blogs.list(1))
          }
      })
  }

  //提交的article表格
  val articleForm = Form(tuple(
    "id" -> number,
    "title" -> nonEmptyText,
    "tags" -> text,
    "content" -> nonEmptyText))

  //登陆用户才能访问的Action
  def ActionWithUser(f: Request[AnyContent] => Result): Action[AnyContent] = Action {
    implicit request =>
      cacheTags
      if (!request.session.get(Constants.User).isDefined) {
        Unauthorized
      } else {
        f(request)
      }
  }

  //用来检查标签
  def ActionWithTags(f: Request[AnyContent] => Result): Action[AnyContent] = Action {
    implicit request =>
      cacheTags
      f(request)
  }

  //用来缓存标签 在blog的Action中都需要检查一下
  def cacheTags = {
    if (!Cache.get(Constants.Categories).isDefined) {
      Cache.set(Constants.Categories, Tag.tags)
    }
    //    println(Cache.getAs[List[String]](Constants.Categories).get.size)
  }

  def refreshTags = {
    Cache.set(Constants.Categories, Tag.tags)
  }
  //格式化时间
  private def timeFormatter(time: Long): String = {
    import java.text.SimpleDateFormat
    val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    formatter.format(new java.util.Date(time))
  }

}